<template>
	<div class="container add_edit">
		<el-form :model="form" ref="ruleForm" :rules="rules" label-width="80px">
			<el-form-item label="上级">
				<el-cascader v-model="form.pid" :show-all-levels="false" :options="classOptions" ref="cascaderObj"
					@change="classChange" filterable
					:props="{ expandTrigger: 'hover', checkStrictly: true, emitPath: false, value: '_id', label: 'name' }"
					clearable>
					<template slot-scope="{ node, data }">
						<div @click="classChange(data._id)" class="cascader">{{data.name}}</div>
					</template>
				</el-cascader>
			</el-form-item>
			<el-form-item label="名称" prop="name" ref="name">
				<el-input v-model="form.name" placeholder="请输入名称" clearable></el-input>
			</el-form-item>
			<el-form-item label="图标">
				<uni-file-picker v-model="imageValue" fileMediatype="image" returnType="object"
					:image-styles="imageStyle" @success="imgUpload" @delete="imgDelete" />
			</el-form-item>
			<el-form-item label="排序">
				<el-input v-model.number="form.sort" placeholder="请输入排序" type="number" :min="1" clearable
					oninput="value = parseInt(value) || 1"></el-input>
				<div class="remark_txt">此处排序将决定前端模块的位置，数字越小，位置越前</div>
			</el-form-item>
			<el-form-item label="状态">
				<el-switch v-model="form.state" active-color="#ff6a6c" inactive-color="#bbb" active-value="启用"
					inactive-value="禁用"></el-switch>
			</el-form-item>
			<el-form-item>
				<el-button :loading="formLoading" round icon="el-icon-check" class="confirm-btn"
					@click="submitForm('ruleForm')">提交</el-button>
				<el-button round icon="el-icon-back" class="return-btn" @click="returnPage">返回</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
	const __name = 'wmzmall-goods-category';
	export default {
		props: {},
		data() {
			return {
				dataId: '',
				formLoading: false,
				form: {
					pid: '',
					name: '',
					img: '',
					sort: 0,
					state: '启用'
				},
				imageValue: null,
				imageStyle: {
					height: '150px',
					width: '150px'
				},
				classOptions: [],
				rules: {
					name: [{
						required: true,
						message: '请输入名称',
						trigger: 'change'
					}]
				}
			};
		},
		methods: {
			async loadData() {
				this.$db[__name].where({
					state: '启用'
				}).totree({
					orderby: 'sort asc',
					startWith: 'pid == ""',
					limitLevel: 1,
					loading: false
				}).then(res => {
					if (res.code == 200) {
						this.setChildren(res.datas);
						this.classOptions = res.datas;
					}
				});

				if (!this.dataId) {
					this.getSort();
					return;
				}

				await this.$db[__name].tofirst(this.dataId).then(res => {
					if (res.code == 200) {
						for (let item in this.form) {
							this.form[item] = res.datas[item];
						}

						if (this.form.img) {
							this.imageValue = {};
							this.imageValue.url = this.form.img;
						}
					}
				});
			},
			submitForm(formName) {
				this.$refs[formName].validate((valid, obj) => {
					// 默认获取第一个未验证 form 属性名
					this.$api.set_unvalidated_form_focus(this, obj);
					if (valid) {
						this.formLoading = true;
						if (!this.dataId) {
							this.$db[__name].add(this.form).then(res => {
								if (res.code == 200) {
									this.getOpenerEventChannel().emit('loadData');
									this.returnPage();
								}
								this.formLoading = false;
							}).catch(() => {
								this.formLoading = false;
							})
						} else {
							this.$db[__name].update(this.dataId, this.form).then(res => {
								if (res.code == 200) {
									this.getOpenerEventChannel().emit('loadData');
									this.returnPage();
								}
								this.formLoading = false;
							}).catch(() => {
								this.formLoading = false;
							})
						}
					}
				});
			},
			getSort() {
				this.$db[__name]
					.where({
						pid: this.form.pid
					})
					.getsort()
					.then(res => {
						if (res.code == 200) {
							this.form.sort = ++res.datas.sort;
						}
					});
			},
			classChange(id) {
				this.form.pid = id || '';
				this.$refs.cascaderObj.dropDownVisible = false;
				if (!this.dataId) {
					this.getSort();
				}
			},
			imgUpload(e) {
				this.form.img = e.tempFilePaths[0];
				this.$refs.validImg.clearValidate();
			},
			imgDelete() {
				this.imageValue = null;
				this.form.img = '';
				this.$refs.ruleForm.validateField('img');
			},
			returnPage() {
				uni.$emit('closeTab');
				uni.redirectTo({
					url: '/pages/goods/classify/goods_classify'
				});
			},
			setChildren(res) {
				res && res.forEach(item => {
					if (item.children && item.children.length <= 0) {
						item.children = null;
						return;
					}

					this.setChildren(item.children);
				});
			}
		},
		created() {
			this.dataId = this.$route.query.id || '';
			this.loadData();
		}
	};
</script>

<style>
	.cascader {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		padding-left: 44px;
		z-index: 99;
	}
</style>
